const express = require("express")
const bcrypt = require("bcrypt")
const jwt = require("jsonwebtoken")
const User = require("../../model/user")
const router = express.Router()
const { secret } = require("../../config/key")

//验证身份-中间件
const isAdmin = async (req, res, next) => {
    //jwt,取Bearer后面的值
    if (!req.headers.authorization) {
        res.status(422).send("未传入token");
    } else {
        const token = req.headers.authorization.split(" ").pop()
        const { _id, username } = jwt.verify(token, secret)
        //查询用户id是否存在
        // console.log(jwt.verify(token, secret));
        const user = await User.findById(_id)
        if (!user) {
            return res.status(422).send("用户错误")
        }
        //用户存在，查看username
        if (username !== user.username) {
            res.status(422).send("用户错误")
        } else {
            // 用户存在，查看权限
            if (user.isAdmin === "0") {
                res.status(409).send("没有权限")
            }
            else if (user.isAdmin === "1") {
                next()
            }
        }
    }

}

//获取用户列表
router.get('/', isAdmin, async (req, res) => {
    // res.send("hello UserRouter")
    const list = await User.find()
    res.send(list)
})

// 注册
router.post("/register", async (req, res) => {
    //判断用户名是否存在
    const user = await User.findOne({ username: req.body.username })
    if (user) {
        return res.status(409).send("该用户已存在")
    }
    const newUser = await new User(req.body).save()
    res.send(newUser)
})

// 登录
router.post("/login", async (req, res) => {
    // 查询用户名是否存在
    const user = await User.findOne({ username: req.body.username })
    if (!user) {
        return res.status(422).send("该用户不存在")
    }
    let isPassword = await bcrypt.compareSync(req.body.password, user.password)
    if (!isPassword) {
        return res.status(422).send("密码错误")

    }
    const { _id, username } = user
    //token 加密
    const token = jwt.sign({ _id, username }, secret, { expiresIn: "24h" })
    res.send(token)
})

//验证
router.get("/verify", async (req, res) => {
    //jwt,取Bearer后面的值
    const token = req.headers.authorization.split(" ").pop()
    const { _id } = jwt.verify(token, secret)
    console.log(_id);

})




module.exports = router